package com.podcstr.service;

import com.podcstr.dao.SeriesDao;
import com.podcstr.entity.Series;
import com.podcstr.service.exception.ServiceException;
import org.apache.log4j.Logger;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author azim
 * @since 5/19/13 
 */

@Stateless
@Local(SeriesService.class)
public class SeriesServiceImpl implements SeriesService {

    private final Logger log = Logger.getLogger(SeriesServiceImpl.class.getName());

    @Inject
    private SeriesDao seriesDao;

    @Override
    public void add(Series series) throws ServiceException {

        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set violations = validator.validate(series);
        if (violations.size() > 0) {

            log.error(violations);
            throw new ServiceException(violations);
        }

        Series existingSeries = seriesDao.findBySeriesName(series.getName());
        if (existingSeries != null) {

            throw new ServiceException("Duplicate Series. This series already exists.");
        }

        try {

            seriesDao.add(series);
            log.info(new Date() + " : Added a new series with name : " + series.getName());
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    @Override
    public List<Series> findAll() {

        log.info(new Date() + " : Returning the list of series.");
        return seriesDao.findAll();
    }

    @Override
    public void delete(long seriesId) {

        seriesDao.delete(seriesId);
        log.info(new Date() + " : Deleting a series with id : " + seriesId + ".");
    }

    @Override
    public void toggleAccess(long seriesId) {

        seriesDao.toggleAccess(seriesId);
        log.info(new Date() + " : Toggling series with id : " + seriesId + " accessable value.");
    }

    @Override
    public void update(Series series) {

        seriesDao.update(series);
        log.info(new Date() + " : Updated the series with id : " + series.getId() + ".");
    }


    @Override
    public Series findBySeriesName(String seriesName) {

        log.info(new Date() + " Returning the series with name : " + seriesName + ".");
        return seriesDao.findBySeriesName(seriesName);
    }

    @Override
    public List<Series> findByUserId(long userId) {

        log.info(new Date() + " : Returning the list of series by user with id : " + userId + ".");
        return seriesDao.findByUserId(userId);
    }

    @Override
    public List<Series> findByTags(String tag) {

        log.info(new Date() + " : Returning the list of series with tag : " + tag + ".");
        return seriesDao.findByTags(tag);
    }
}
